﻿using System;
using System.Text;
using System.Xml;
using System.Xml.XPath;

namespace Allegro.TaskExecution
{
    ///<summary>
    ///</summary>
    public class Blob : PersistentItem
    {
        private const int BlockSize = 30000;

        byte[] _byteArray = null;
        ///<summary>
        ///</summary>
        public Blob()
        {

        }
        ///<summary>
        ///</summary>
        ///<param name="content"></param>
        public Blob(byte[] content)
        {
            _byteArray = content;
        }
        ///<summary>
        ///</summary>
        public byte[] ByteArray
        {
            get { return _byteArray; }
            set { _byteArray = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="persistenceContext"></param>
        protected override void SaveContent(XmlWriter writer, IXmlPersistenceContext persistenceContext)
        {
            base.SaveContent(writer, persistenceContext);

            int nBlocks = _byteArray.Length / BlockSize + 1;
            for (int i = 0; i < nBlocks; i++)
            {
                writer.WriteStartElement("B", XmlNamespace);
                int i1 = i * BlockSize;
                int length = (i + 1) * BlockSize < _byteArray.Length - 1
                                 ? BlockSize
                                 : _byteArray.Length - i1;
                writer.WriteBase64(_byteArray, i1, length);
                writer.WriteEndElement();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemNode"></param>
        /// <param name="persistenceContext"></param>
        protected override void LoadContent(XPathNavigator itemNode, IXmlPersistenceContext persistenceContext)
        {
            base.LoadContent(itemNode, persistenceContext);

            XmlNamespaceManager nsMgr = persistenceContext.NamespaceManager;
            // _testBytes
            XPathNodeIterator bytesNodes = itemNode.Select("al:B", nsMgr);
            if (bytesNodes.Count > 0)
            {
                StringBuilder bytesBuilder = new StringBuilder(bytesNodes.Count * BlockSize);
                foreach (XPathNavigator bytesNode in bytesNodes)
                {
                    bytesBuilder.Append(bytesNode.Value);
                }
                _byteArray = Convert.FromBase64String(bytesBuilder.ToString());
            }
        }

    }
}

